package cn.com.connext.scrm.service;

import cn.com.connext.scrm.domain.master.*;
import cn.com.connext.scrm.repository.master.IndexModuleConfigChildRepository;
import cn.com.connext.scrm.repository.master.IndexModuleConfigRepository;
import cn.com.connext.scrm.repository.master.IndexModuleRepository;
import cn.com.connext.scrm.repository.master.SecondActivityRepository;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.web.rest.vm.*;
import com.connext.common.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.ZonedDateTime;
import java.util.*;


@Service
@Transactional
public class IndexModuleConfigService {

    @Autowired
    private IndexModuleConfigRepository imcRepository;
    @Autowired
    private IndexModuleRepository imRepository;
    @Autowired
    private IndexModuleConfigChildRepository imcchildRepository;
    @Autowired
    private SecondActivityRepository smRepository;
    @Autowired
    private RecordOpenWindowService recordOpenWindowService;

    public JsonResult save(IndexModuleConfigAddVM vm) {
        JsonResult result =new JsonResult();
        if(vm !=null){
            List<IndexModuleConfigVM> addList = vm.getAddList();
            if(addList !=null && addList.size() >0){
                IndexModuleConfig ac= imcRepository.findOrderLimitOne();
                long b =0;
                if(ac !=null && ac.getConfigOrder() !=null){
                    b=ac.getConfigOrder();
                }
                List<IndexModuleConfigChild> allList = new ArrayList<>();
                IndexModuleConfig config =null;
                IndexModuleConfigChild cl = null;
                for (int i =0;i <addList.size(); i++) {
                    config =new IndexModuleConfig();
                    config.setType(addList.get(i).getType());
                    if(addList.get(i).getIsAutoLb() !=null){
                        config.setIsAutoLb(addList.get(i).getIsAutoLb());
                    }
                    if(addList.get(i).getIsAppend() !=null){
                        config.setIsAppend(addList.get(i).getIsAppend());
                    }
                    config.setComponentName(addList.get(i).getComponentName());
                    b +=1;
                    config.setConfigOrder(b);
                    IndexModuleConfig entity = imcRepository.saveAndFlush(config);
                    List<IndexModuleConfigChild> lbtList = addList.get(i).getLbtList();
                    cl = new IndexModuleConfigChild();
                    if(StringUtils.isNotEmpty(addList.get(i).getUrl())){
                        cl.setUrl(addList.get(i).getUrl());
                        cl.setIndexModuleConfigId(entity.getId());
                        if(StringUtils.isNotEmpty(addList.get(i).getLinkPage())){
                            cl.setLinkPage(addList.get(i).getLinkPage());
                        }
                        if(StringUtils.isNotEmpty(addList.get(i).getLeftLinkPage())){
                            cl.setLeftLinkPage(addList.get(i).getLeftLinkPage());
                        }
                        if(StringUtils.isNotEmpty(addList.get(i).getRightLinkPage())){
                            cl.setRightLinkPage(addList.get(i).getRightLinkPage());
                        }
                        if(StringUtils.isNotEmpty(addList.get(i).getAppId())){
                            cl.setAppId(addList.get(i).getAppId());
                        }
                        allList.add(cl);
                    }else{
                        if(lbtList !=null && lbtList.size() >0){
                            for (IndexModuleConfigChild child:lbtList) {
                                child.setIndexModuleConfigId(entity.getId());
//                                child.setUrl(child.getUrl());
                                allList.add(child);
                            }
                        }
                    }
                }
                imcchildRepository.save(allList);
            }
            result.setState(0);
            result.setMessage("添加成功");
        }else{
            result.setState(-1);
            result.setMessage("参数异常!");
        }
        return result;
    }

  //查询所有组件
    public JsonResult findAllModule() {
        JsonResult result = new JsonResult();
        List<IndexModuleConfig> list = imcRepository.findAll();
        Collections.sort(list, Comparator.comparing(IndexModuleConfig::getId));
        if(list !=null && list.size() >0){
            List<IndexModuleConfigVM> returnList =new ArrayList<>();
            IndexModuleConfigVM vm =null;
            for (IndexModuleConfig config:list ) {
                vm =new IndexModuleConfigVM();
                List<IndexModuleConfigChild> indexChildList = imcchildRepository.findByIndexModuleConfigId(config.getId());
                vm.setId(config.getId());
                vm.setComponentName(config.getComponentName());
                vm.setType(config.getType());
                vm.setIsAppend(config.getIsAppend());
//                vm.setLinkPage(config.get);
                if(indexChildList!=null && indexChildList.size() >0) {
                    if (config.getType() == 1) {
                        //轮播图
                        vm.setLbtList(indexChildList);
                        vm.setTitle("轮播图");
                        if(config.getIsAutoLb() !=null){
                            vm.setIsAutoLb(config.getIsAutoLb());
                        }
//                        vm.setLinkPage(IndexChildList.get(0).getLinkPage());
                    } else if (config.getType() == 2) {
                        //图片
                        if(StringUtils.isNotEmpty(indexChildList.get(0).getLeftLinkPage())){
                            vm.setLeftLinkPage(indexChildList.get(0).getLeftLinkPage());
                        }
                        if(StringUtils.isNotEmpty(indexChildList.get(0).getRightLinkPage())){
                            vm.setRightLinkPage(indexChildList.get(0).getRightLinkPage());
                        }
                        vm.setImgUrl(indexChildList.get(0).getUrl());
                        vm.setTitle("图片");
                        vm.setIndexModuleConfigChildId(indexChildList.get(0).getId());
                    }
                    if(StringUtils.isNotEmpty(indexChildList.get(0).getLinkPage())){
                        vm.setLinkPage(indexChildList.get(0).getLinkPage());
                    }
                    if(StringUtils.isNotEmpty(indexChildList.get(0).getAppId())){
                        vm.setAppId(indexChildList.get(0).getAppId());
                    }
                }
                returnList.add(vm);
            }
            result.setData(returnList);
            result.setState(0);
        }
        return result;
    }

    public JsonResult addIndexModule(IndexModule entity) {
        JsonResult result =new JsonResult();
        if(entity !=null){
            imRepository.saveAndFlush(entity);
            result.setMessage("活动组件模块配置完成");
            result.setState(0);
        }else{
            result.setMessage("参数不能为空!");
            result.setState(-1);
        }
        return result;
    }

    public JsonResult findModuleBySecondActivityId(String IndexId) {
        JsonResult result =new JsonResult();
        if(IndexId !=null){
            List<IndexModule> list = imRepository.findBySecondActivityId(IndexId);
            Collections.sort(list, Comparator.comparing(IndexModule::getModuleOrder));
            List<IndexModuleConfigVM> returnList =new ArrayList<>();
            if(list !=null && list.size() >0){
                IndexModuleConfigVM vm =null;
                for (IndexModule config:list ) {
                    if (config.getIndexModuleConfigId() != null) {
                        List<IndexModuleConfigChild> indexChildList = imcchildRepository.findByIndexModuleConfigId(config.getIndexModuleConfigId());
                        IndexModuleConfig con = imcRepository.findOne(config.getIndexModuleConfigId());
                        vm = new IndexModuleConfigVM();
                        vm.setSecondActivityId(IndexId);
                        vm.setId(con.getId());
                        vm.setComponentName(con.getComponentName());
                        vm.setType(con.getType());
                        if (indexChildList != null && indexChildList.size() > 0) {
                            if (con != null) {
                                if (con.getType() == 1) {
                                    //轮播图
                                    if(con.getIsAutoLb() !=null){
                                        vm.setIsAutoLb(con.getIsAutoLb());
                                    }
                                    vm.setLbtList(indexChildList);
                                    vm.setTitle("轮播图");
                                }  else if (con.getType() == 2) {
                                    //图片
                                    vm.setImgUrl(indexChildList.get(0).getUrl());
                                    vm.setTitle("图片");
                                    vm.setUrl(indexChildList.get(0).getUrl());
                                    vm.setIsAppend(con.getIsAppend());
                                    if(StringUtils.isNotEmpty(indexChildList.get(0).getLeftLinkPage())){
                                        vm.setLeftLinkPage(indexChildList.get(0).getLeftLinkPage());
                                    }
                                    if(StringUtils.isNotEmpty(indexChildList.get(0).getRightLinkPage())){
                                        vm.setRightLinkPage(indexChildList.get(0).getRightLinkPage());
                                    }
                                }
                                if(StringUtils.isNotEmpty(indexChildList.get(0).getLinkPage())){
                                    vm.setLinkPage(indexChildList.get(0).getLinkPage());
                                }
                                if(StringUtils.isNotEmpty(indexChildList.get(0).getAppId())){
                                    vm.setAppId(indexChildList.get(0).getAppId());
                                }
                                vm.setType(con.getType());
                                vm.setId(con.getId());
                                returnList.add(vm);
                            }
                        }
                    }
                }
            }
            result.setData(returnList);
            result.setState(0);
        }else{
            result.setMessage("参数IndexId不能为空!");
            result.setState(-1);
        }
        return result;
    }

    public JsonResult delete(IndexModule entity) {
        JsonResult result =new JsonResult();
        imRepository.delete(entity.getId());
        result.setMessage("删除成功");
        result.setState(0);
        return result;
    }

    public JsonResult addIndexModuleList(IndexModuleVM vm) {
        JsonResult result =new JsonResult();
        if(StringUtils.isNotEmpty(vm.getSecondActivityId())){
            //删除该活动原有组件
            imRepository.deleteBySecondActivityId(vm.getSecondActivityId());
        }
        if(vm !=null && vm.getList().size() > 0){
            List<IndexModule> list = vm.getList();
            if(list !=null && list.size() >0){
                long i =0;
                for (IndexModule am:list) {
                    i+=1;
                    am.setModuleOrder(i);
                }
                imRepository.save(list);
            }
        }
        result.setMessage("操作成功");
        result.setState(0);
        return result;
    }

    public JsonResult deleteComponent(IndexModuleConfigVM vm) {
        JsonResult result =new JsonResult();
        if(vm.getId() !=null){
            imcRepository.delete(vm.getId());
            imcchildRepository.deleteByIndexModuleConfigId(vm.getId());
            result.setMessage("操作成功");
            result.setState(0);
        }else{
            result.setMessage("参数不能为空");
            result.setState(-1);
        }
        return result;
    }


    public JsonResult findById(Long id) {
        JsonResult result =new JsonResult();
        if(id !=null){
            IndexModuleConfig con = imcRepository.findOne(id);
            List<IndexModuleConfigChild> indexChildList = imcchildRepository.findByIndexModuleConfigId(id);
            IndexModuleConfigVM vm =new IndexModuleConfigVM();
            if(indexChildList !=null && indexChildList.size() >0){
               if(con !=null){
                   if (con.getType() == 1) {
                       //轮播图
                       //轮播图
                       if(con.getIsAutoLb() !=null){
                           vm.setIsAutoLb(con.getIsAutoLb());
                       }
                       vm.setLbtList(indexChildList);
                       vm.setTitle("轮播图");
                   } else if (con.getType() == 2) {
                       //图片
                       vm.setImgUrl(indexChildList.get(0).getUrl());
                       vm.setTitle("图片");
                       vm.setUrl(indexChildList.get(0).getUrl());
                       vm.setIsAppend(con.getIsAppend());
                       if(StringUtils.isNotEmpty(indexChildList.get(0).getLeftLinkPage())){
                           vm.setLeftLinkPage(indexChildList.get(0).getLeftLinkPage());
                       }
                       if(StringUtils.isNotEmpty(indexChildList.get(0).getRightLinkPage())){
                           vm.setRightLinkPage(indexChildList.get(0).getRightLinkPage());
                       }
                   }
                   if(StringUtils.isNotEmpty(indexChildList.get(0).getLinkPage())){
                       vm.setLinkPage(indexChildList.get(0).getLinkPage());
                   }
                   if(StringUtils.isNotEmpty(indexChildList.get(0).getAppId())){
                       vm.setAppId(indexChildList.get(0).getAppId());
                   }
                   vm.setType(con.getType());
                   vm.setComponentName(con.getComponentName());
               }
               result.setState(0);
               result.setData(vm);
            }
        }else{
            result.setMessage("参数不能为空");
            result.setState(-1);
        }
        return result;
    }

    public JsonResult editCoupon(IndexModuleConfigEditVM vm) {
        JsonResult result =new JsonResult();
        IndexModuleConfig con = imcRepository.findOne(vm.getId());
        //如果修改了类型，删除原有子类
        if(con.getType() !=vm.getType()){
            imcchildRepository.deleteByIndexModuleConfigId(vm.getId());
            con.setType(vm.getType());
        }
        if (vm.getIsAutoLb()!=null) {
            con.setIsAutoLb(vm.getIsAutoLb());
        }
        if (vm.getIsAppend()!=null) {
            con.setIsAppend(vm.getIsAppend());
        }
        con.setComponentName(vm.getComponentName());
        imcRepository.saveAndFlush(con);


        if (con.getType() == 1) {
            //轮播图
            List<Long> idList =new ArrayList<>();
            IndexModuleConfigChild indexModule =null;
            List<IndexModuleConfigChild> addList = new ArrayList<>();
            if(vm.getLbtList() !=null && vm.getLbtList().size() >0){
                List<IndexModuleConfigChild> list = vm.getLbtList();
                for (int i =0;i <list.size() ;i ++ ) {
                    indexModule = new IndexModuleConfigChild();
                    if(list.get(i).getId() !=null){
                        indexModule.setId(list.get(i).getId());
                        idList.add(list.get(i).getId());
                    }
                    if(vm.getId()!=null){
                        indexModule.setIndexModuleConfigId(vm.getId());
                    }
                    if(StringUtils.isNotEmpty(list.get(i).getLinkPage())){
                        indexModule.setLinkPage(list.get(i).getLinkPage());
                    }
                    if(StringUtils.isNotEmpty(list.get(i).getAppId())){
                        indexModule.setAppId(list.get(i).getAppId());
                    }
                    indexModule.setUrl(list.get(i).getUrl());
                    addList.add(indexModule);
                }
            }
            if(idList.size() >0){
                imcchildRepository.deleteByCondition(idList,vm.getId());
           }
            imcchildRepository.save(addList);
        } else{
            //图片
            IndexModuleConfigChild configChild = new IndexModuleConfigChild();
            if(vm.getIndexModuleConfigChildId()!=null){
                configChild.setId(vm.getIndexModuleConfigChildId());
            }
            if(vm.getId()!=null){
                configChild.setIndexModuleConfigId(vm.getId());
            }
            if(StringUtils.isNotEmpty(vm.getLinkPage())){
                configChild.setLinkPage(vm.getLinkPage());
            }
            if(StringUtils.isNotEmpty(vm.getLeftLinkPage())){
                configChild.setLeftLinkPage(vm.getLeftLinkPage());
            }
            if(StringUtils.isNotEmpty(vm.getRightLinkPage())){
                configChild.setRightLinkPage(vm.getRightLinkPage());
            }
            if(StringUtils.isNotEmpty(vm.getAppId())){
                configChild.setAppId(vm.getAppId());
            }
            configChild.setUrl(vm.getUrl());
            imcchildRepository.saveAndFlush(configChild);
        }
        result.setMessage("编辑成功");
        result.setState(0);
        return result;
    }


    public JsonResult addSecondActivity(SecondActivity entity) {
        JsonResult result =new JsonResult();
        if(entity !=null){
            entity.setCreateTime(ZonedDateTime.now());
            smRepository.saveAndFlush(entity);
            result.setMessage("活动首页信息维护成功");
            result.setState(0);
        }else{
            result.setMessage("参数不能为空!");
            result.setState(-1);
        }
        return result;
    }

    public JsonResult deleteSecondActivity(SecondActivity entity) {
        JsonResult result =new JsonResult();
        if(entity !=null && entity.getId() !=null){
            smRepository.delete(entity.getId());
            result.setMessage("删除成功");
            result.setState(0);
        }else{
            result.setMessage("参数不能为空!");
            result.setState(-1);
        }
        return result;
    }

    public Page<SecondActivity> findByPage(MemberIndexModulePageVM vm) {
        PageRequest pageRequest = new PageRequest(vm.getPage(), vm.getPageSize(), Sort.Direction.DESC, "createTime");
        Page page = smRepository.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                List<Predicate> list = new LinkedList<>();
                Predicate[] pre = new Predicate[list.size()];
                return query.where(list.toArray(pre)).getRestriction();
            }
        }, pageRequest);
        return page;
    }

    public JsonResult recordOpenWindowByUnionId(RecordOpenWindow entity) {
        JsonResult result = new JsonResult();
        if(entity ==null || StringUtils.isEmpty(entity.getUnionId())){
            result.setState(-1);
            result.setMessage("参数错误!");
        }else{
            Date date = new Date();
            String createTime = DateUtil.format(date, "yyyy-MM-dd");
            RecordOpenWindow byUnionIdAndcreateTime = recordOpenWindowService.findByUnionIdAndCreateTime(entity.getUnionId(), createTime);
            if(byUnionIdAndcreateTime ==null){
                entity.setCreateTime(new Date());
                recordOpenWindowService.save(entity);
                result.setState(0);
                result.setMessage("记录成功");
            }else{
                result.setState(1);
                result.setMessage("该会员今日已弹窗记录");
            }
        }
        return result;
    }


}
